/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2010
Version 0.1
=======================================================*/
#include "httpd/DiskFile.h"
#include "ACSConfig.h"

namespace acs
{

DiskFile::DiskFile() : fileSize(0), lastModified(0)
{

}

DiskFile::DiskFile(const boost::filesystem::path& path, char *content, unsigned long size, std::time_t modified, const std::string& mime) : filePath(path), fileContent(content), fileSize(size), lastModified(modified), mimeType(mime)
{

}

DiskFile::DiskFile(const DiskFile& f) : filePath(f.filePath), fileContent(f.fileContent), fileSize(f.fileSize), lastModified(f.lastModified), lastModifiedString(f.lastModifiedString), mimeType(f.mimeType)
{

}


void DiskFile::update()
{
	fileSize = boost::numeric_cast<std::streamsize>(boost::filesystem::file_size( filePath ));
	lastModified = boost::filesystem::last_write_time( filePath );
	lastModifiedString = pion::net::HTTPTypes::get_date_string( lastModified );
}

void DiskFile::read()
{
	fileContent.reset(new char[fileSize]);

	boost::filesystem::ifstream fileStream;
	fileStream.open(filePath, std::ios::in | std::ios::binary);

	if (!fileStream.is_open() || !fileStream.read(fileContent.get(), fileSize))
	{
		Throw(rgcpp::MissingResourceException(filePath.file_string()));
	}
}

bool DiskFile::checkUpdated()
{
	std::streamsize cur_size = boost::numeric_cast<std::streamsize>(boost::filesystem::file_size( filePath ));
	std::time_t cur_modified = boost::filesystem::last_write_time( filePath );


	if (cur_modified == lastModified && cur_size == fileSize)
		return false;

	fileSize = cur_size;
	lastModified = cur_modified;
	lastModifiedString = pion::net::HTTPTypes::get_date_string(lastModified);

	read();

	return true;
}

const boost::filesystem::path& DiskFile::getFilePath() const
{
	return filePath;
}

char* DiskFile::getFileContent()
{
	return fileContent.get();
}

bool DiskFile::hasFileContent() const
{
	return fileContent;
}

unsigned long DiskFile::getFileSize() const
{
	return fileSize;
}

std::time_t DiskFile::getLastModified() const
{
	return lastModified;
}

const std::string& DiskFile::getLastModifiedString() const
{
	return lastModifiedString;
}

const std::string& DiskFile::getMimeType() const
{
	return mimeType;
}

void DiskFile::setFilePath(const boost::filesystem::path& p)
{
	filePath = p;
}

void DiskFile::appendFilePath(const std::string& p)
{
	filePath /= p;
}

void DiskFile::setMimeType(const std::string& mimeType)
{
	this->mimeType = mimeType;
}

void DiskFile::resetFileContent(unsigned long n)
{
	if (n == 0)
		fileContent.reset();
	else
		fileContent.reset(new char[n]);
}

}
